<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head><title>Grails Maps- Cities<g:if test="${state}">
  in ${state.stateName}
</g:if></title>
  <meta name="layout" content="main"/>

  <script type="text/javascript">
    var map;


    /* lets do some serious progressive enhancement to (just) this page.
     * Functionality is above and beyond json based version */
    (function($) {
      $(document).ready(function() {
        initAjax();
      });

      function initAjax() {

        $(window).unload(function () {
          GUnload();
        });

        /* Add drag and drop */
        $("table#city-list tr").not(':first-child').sortable({
          connectWith: '#map-wrapper',
          handle: 'a',
          helper:'clone',
          stop: function(event, ui) {
            var chk = $(".city-check", this);
            if (!($(chk).is(':checked'))) {
              $(chk).attr('checked', true);
              addMarker(chk);
            }

          }
        }).disableSelection();//disable selection of text


        $("#map-wrapper").droppable().disableSelection();

        /* End drag and drop */

        /* load city via ajax when a city link is clicked */
        $("td.city-link-cell a").unbind('click').click(function(event) {
          event.preventDefault();
          loadCity(this);
        });

        /* add some checkboxes to the city list that don't exist in the markup*/
        $("td.city-link-cell").prepend($('<input class="city-check" type="checkbox"/>'));
        /* add an event to the new checkbox click */
        $(".city-check").unbind('click').click(function() {
          addMarker(this);
        });

        /* take over the pagination click event */
        $('.pagination-wrapper  a').unbind('click').click(function(event) {
          event.preventDefault();
          loadCitiesFromURL($(this).attr("href"));

        });

        /* take over the search form submit button */
        $('#search-form input#search').unbind('click').click(function(event) {
          event.preventDefault();
          search($('input[name=searchText]').val());

        });


      }

    /* add a map marker when user checks a city.
    would  be nice to cache the latlong
     */
      function addMarker(chk) {
        var cityId = $(chk).siblings('a').attr("id");

        //load the city info via json
        if ($(chk).is(':checked')) {
          $.getJSON(BASE_URL + "/city/show/" + cityId + "?format=json", loadCityJson);
        }
        else { //remove marker
          var a = $('.city-check + a[id=' + cityId + ']');
          var marker = $(a).data("marker");
          map.removeOverlay(marker);
        }

      }

      /* user clicks search button */
      function search(searchText) {
        /* full ajax syntax */
        $.ajax({
          type:'GET',
          url:'${state?.id}',
          dataType:'html',
          cache:false,
          data:'max=${params.max?params.max:10}&offset=${params.offset?params.offset:0}&searchText=' + searchText,
          success:function(html) {
            loadCitiesFromURLResponse(html);
          } ,
          beforeSend:function() {
            $('#ajax-status').text('Requesting...');
            $('#ajax-status').show();
          },

          complete:function() {
            $('#ajax-status').text('Complete');
            $('#ajax-status').fadeOut('slow');
          },
          error:function() {
            $('#ajax-status').text('Ajax error occurred');
            $('#ajax-status').fadeIn();
          }

        });

        /* Could do this instead like this
         $.get("${state?.id}",
         {max:${params.max?params.max:10},
         offset:${params.offset?params.offset:0},
         searchText:searchText },
         loadCitiesFromURLResponse);
         }
         */

      }


      /* load the exact city link from the anchor */
      function loadCitiesFromURL(href) {
      $.get(href, loadCitiesFromURLResponse);

      }

      /* we have a city response as html
      * is it easier to process json?*/
      function loadCitiesFromURLResponse(htmlString) {
        /*Need to break apart the results since are interested in two separate section*/

        var htmlNode = $(htmlString);

        //replace the old element
        $('.pagination-wrapper').replaceWith($('.pagination-wrapper', htmlNode));
        $('table#city-list').replaceWith($('table#city-list', htmlNode));


        //now ajaxify the result
        initAjax();
        /*jquery on ready will be called for the new fragement individually.
         Would be more optimal to return as json*/

      }



  /* load the google map and store the marker as data in the <a> for later use when removing*/
      function loadCityJson(city) {

        map.setCenter(new GLatLng(city.latitude, city.longitude), 6);
        map.setUIToDefault();
        var point = new GLatLng(city.latitude, city.longitude);
        var marker = new GMarker(point)
        map.addOverlay(marker);
        var a = $('.city-check + a[id=' + city.id + ']');
        $(a).data("marker", marker);


      }

      /* load the city detail via the existing city link*/
      function loadCity(cityLink) {

        var id = $(cityLink).attr("id");
        $.get(BASE_URL + "/city/show/" + id,
        {max:${params.max?params.max:10},
          offset:${params.offset?params.offset:0}
        },loadCityResponse);

      }

      /* process the city load results in a pop up dialog box
      could have made this modal.
       */
      function loadCityResponse(data) {

        var result = $(data);
        var cityDetail = $('#city-detail');
        $('#map-wrapper').hide();
        $(cityDetail).append($('#city-wrapper', result))
                .dialog({ title: 'City Detail',
          height:600,
          width:600,
          close: function(event, ui) {
            $('#map-wrapper').show();
            $(cityDetail).dialog('destroy');
            $(cityDetail).empty();
          }
        }
       );

        //add a new map to the detail
        $(cityDetail).append($('<div id="city-map-wrapper"><div id="city-map"/></div>'));
        var cityMap = new google.maps.Map2(document.getElementById("city-map"));

        var latitude = $('#city-latitude', cityDetail).text();
        var longitude = $('#city-longitude', cityDetail).text();
        cityMap.setCenter(new GLatLng(latitude, longitude), 12);

        var point = new GLatLng(latitude, longitude);
        cityMap.addOverlay(new GMarker(point));
        cityMap.setUIToDefault();


      }

    })(jQuery);
  </script>

  <script type="text/javascript">

    google.load("maps", "2.x");
    google.setOnLoadCallback(initialize);


    function initialize() {

      map = new google.maps.Map2(document.getElementById("map"));
    <g:if test="${cities}">
      map.setCenter(new GLatLng(${cities?.get(0)?.latitude}, ${cities?.get(0)?.longitude}), 6);
    </g:if>
    <g:else>
      map.setCenter(new GLatLng(40.00, -91.00), 3);
    </g:else>
      map.setUIToDefault();
    }





  </script>

</head>
<body>
<div id="state-wrapper">
  <g:include controller="state" action="list" params="[stateId:state?.id]"/>
</div>
<div id="main-content">
  <div id="page-info">
    <div id="page-header">

      <div>
        <g:form action="listCities" name="search-form">
          <g:hiddenField name="id" value="${state?.id}"/>
          <label>Search</label><span><g:textField name="searchText" value="${searchText}"/></span>
          <g:submitButton name="search" value="Search"/>
        </g:form>
      </div>
    </div>

    <g:if test="${cities}">
      <table id="city-list">
        <g:if test="${state}">
          <caption>Cities in ${state.stateName}</caption>
        </g:if>
        <tr>
          <th>City Name</th>
          <g:if test="${!state}">
            <th>State</th>
          </g:if>
        </tr>
        <g:each in="${cities}" var="city">
          <tr>
            <td class="city-link-cell">
              <g:link controller="city" action="show" id="${city.id}" elementId="${city.id}"
                      params="${[stateId:stateId, searchText:params.searchText,
          max:params.max, sort:params.sort, order:params.order, offset:params.offset]}">${city.cityName}</g:link>
            </td>
            <g:if test="${!state}">
              <td>${city.state.stateName}</td>
            </g:if>
          </tr>

        </g:each>
      </table>
    </g:if>
    <g:else>
      <table id="city-list">

        <caption id="no-results">
          No cities found!
        </caption>
      </table>
    </g:else>
    <div class="pagination-wrapper">
      <g:paginate id="${stateId}" prev="Prev" next="Next"
              params="${[stateId:stateId, searchText:params.searchText]}" maxsteps="5" controller="state" action="listCities" total="${cityCount}"/>
    </div>
  </div>
  <div id="city-detail">

  </div>
  <div id="map-wrapper">
    <div id="map">
    <!-- if we have at least one city, center the map on the first one, otherwise go back the the us map -->
      <g:if test="${cities}">
        <img src="http://maps.google.com/maps/api/staticmap?center=${cities[0].latitude},${cities[0].longitude}&zoom=6&size=500x300&key=ABQIAAAAiVvLfVjjB1KmQhUm1SwcpBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQQKUpurwoNEcA7_Vi5pMFL-IGerw&sensor=false"/>
      </g:if>
      <g:else>
        <img src="http://maps.google.com/maps/api/staticmap?center=40.00,-91.00}&zoom=6&size=500x300&key=ABQIAAAAiVvLfVjjB1KmQhUm1SwcpBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQQKUpurwoNEcA7_Vi5pMFL-IGerw&sensor=false"/>

      </g:else>
    </div>
  </div>
  <div id="ajax-status">ajax status</div>

</div>
</body>
</html>